/**
 * 
 */
package org.t2.backstage.module.giftcode.service;

import java.util.ArrayList;
import java.util.List;

import org.banish.sql.core.util.QuerySet;
import org.gaming.backstage.PageData;
import org.gaming.service.service.AbstractService;
import org.gaming.tool.RandomUtil;
import org.springframework.stereotype.Service;
import org.t2.backstage.module.giftcode.model.GiftCode;
import org.t2.backstage.module.giftcode.model.GiftCodeRandomLog;

/**
 * @author YY
 *
 */
@Service
public class GiftCodeRandomLogService extends AbstractService<GiftCodeRandomLog> {

	private static char[] letters = new char[] { '2', '3', '4', '5', '6', '7', '8', '9', 
			'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
	
	private void tryInsertCodes(List<GiftCodeRandomLog> giftCodes) {
		// 先尝试批量插入，批量插入失败则逐个插入
		try {
			// 分批插入礼包码，存在随机码重复的情况
			this.repository().insertAll(giftCodes);
		} catch (Exception e) {
			for (GiftCodeRandomLog temp : giftCodes) {
				try {
					this.insert(temp);
				} catch (Exception e2) {
					// 重复的礼包码丢弃掉
				}
			}
		}
	}

	private String randomCode(int codeBit) {
		String code = "";
		for (int i = 0; i < codeBit; i++) {
			int index = RandomUtil.closeOpen(0, letters.length);
			code += letters[index];
		}
		return code;
	}
	
	
	public void trySpawnCodes(GiftCode giftCode, int codeBit) {
		List<GiftCodeRandomLog> randomCodes = new ArrayList<>();
		for(int i = 0; i < giftCode.getNum(); i++) {
			GiftCodeRandomLog randomCode = new GiftCodeRandomLog();
			randomCode.setGiftId(giftCode.getId());
			randomCode.setCode(randomCode(codeBit));
			randomCodes.add(randomCode);
			if(randomCodes.size() >= 100) {
				tryInsertCodes(randomCodes);
				randomCodes.clear();
			}
		}
		if(!randomCodes.isEmpty()) {
			tryInsertCodes(randomCodes);
			randomCodes.clear();
		}
	}

	@Override
	public void mergeServer(int mergeDbZoneId) {
		//不用实现
	}
	
	public PageData<GiftCodeRandomLog> query(QuerySet querySet) {
		querySet.formWhere();
		List<GiftCodeRandomLog> result = this.repository().getBaseDao().queryListWhere(querySet.getWhere(), querySet.getParams());
		long count = repository().getBaseDao().countWhere(querySet.getCountWhere(), querySet.getCountParams());
		PageData<GiftCodeRandomLog> queryPage = new PageData<>(count, result);
		return queryPage;
	}
}
